<template>
  <view class="job-detail-page">
    <!-- 顶部导航栏 -->
    <!-- <view class="navbar flex items-center justify-between px-[30rpx] py-[20rpx] bg-white border-b border-gray-100">
      <view class="back-btn" @click="navigateBack">
        <IconFont name="arrowleft" size="36rpx" />
      </view>
      <text class="title text-[32rpx] font-bold">职位详情</text>
      <view class="share-btn" @click="shareJob">
        <IconFont name="share" size="36rpx" />
      </view>
    </view> -->
    <PageHeader title="职位详情" :showBack="true" :onlyBack="false" />

    <!-- 职位卡片 -->
    <view class="job-card bg-white p-[30rpx] mb-[20rpx]">
      <!-- 招聘类型标签 -->
      <view class="recruitment-tag" v-if="jobInfo.recruitmentType === 1">
        <text class="tag-text">特殊招聘</text>
      </view>

      <!-- 职位名称 -->
      <text class="job-title text-[34rpx] font-bold mb-[16rpx] block">{{
        jobInfo.position_name
      }}</text>

      <!-- 薪资 -->
      <text class="salary text-[36rpx] text-red-500 font-bold mb-[20rpx] block">
        ¥{{ jobInfo.salary_min }}-{{ jobInfo.salary_max }}/月
      </text>

      <!-- 基本信息行 -->
      <view
        class="basic-info flex flex-wrap gap-x-[40rpx] gap-y-[16rpx] mb-[24rpx]"
      >
        <text class="info-item text-[26rpx] text-gray-600">{{
          jobInfo.location
        }}</text>
        <text class="info-item text-[26rpx] text-gray-600">{{
          jobInfo.experience
        }}</text>
        <text class="info-item text-[26rpx] text-gray-600">{{
          jobTypeText
        }}</text>
      </view>

      <!-- 公司信息 -->
      <view class="company-info flex items-center mb-[20rpx]">
        <view
          class="company-logo w-[80rpx] h-[80rpx] bg-gray-100 rounded-[10rpx] flex items-center justify-center mr-[20rpx]"
        >
          <IconFont name="company" size="40rpx" class="text-gray-400" />
        </view>
        <view class="company-details">
          <text class="company-name text-[30rpx] font-bold">{{
            jobInfo.corporate_name
          }}</text>
          <text class="publish-time text-[24rpx] text-gray-500 mt-[8rpx] block">
            发布于 {{ formatPublishTime(jobInfo.create_time) }}
          </text>
        </view>
      </view>
    </view>

    <!-- 职位详情 -->
    <view class="job-details bg-white p-[30rpx] mb-[20rpx]">
      <text
        class="section-title text-[30rpx] font-bold mb-[20rpx] block pb-[10rpx] border-b border-gray-100"
      >
        职位描述
      </text>
      <view
        class="description-content text-[26rpx] text-gray-700 leading-[1.8]" v-if="jobInfo?.description"
      >
        <text
          v-for="(paragraph, index) in jobInfo?.description?.split('\n')"
          :key="index"
        >
          {{ paragraph }}
          <view class="h-[20rpx]"></view>
        </text>
      </view>
    </view>

    <!-- 职位标签 -->
    <view class="job-tags bg-white p-[30rpx] mb-[20rpx]">
      <text class="section-title text-[30rpx] font-bold mb-[20rpx] block"
        >职位标签</text
      >
      <view class="tags-container flex flex-wrap gap-[16rpx]" v-if="jobInfo?.labels">
        <view
          v-for="(tag, index) in jobInfo?.labels?.split(',')"
          :key="index"
          class="tag bg-blue-50 text-blue-600 px-[20rpx] py-[12rpx] rounded-[30rpx] text-[26rpx] border border-blue-100"
        >
          {{ tag }}
        </view>
      </view>
    </view>

    <!-- 联系方式 -->
    <!-- <view class="contact-info bg-white p-[30rpx] mb-[120rpx]">
      <text
        class="section-title text-[30rpx] font-bold mb-[20rpx] block pb-[10rpx] border-b border-gray-100"
      >
        联系方式
      </text>
      <view class="contact-item flex items-center mb-[24rpx]">
        <IconFont name="phone" size="30rpx" class="text-gray-500 mr-[20rpx]" />
        <text class="contact-text text-[26rpx]">{{
          jobInfo.contactPhone
        }}</text>
      </view>
      <view class="contact-item flex items-center">
        <IconFont name="email" size="30rpx" class="text-gray-500 mr-[20rpx]" />
        <text class="contact-text text-[26rpx]">{{
          jobInfo.contactEmail
        }}</text>
      </view>
    </view> -->

    <!-- 底部操作栏 -->
    <view
      class="bottom-bar fixed bottom-0 left-0 right-0 bg-white p-[20rpx] border-t border-gray-100 flex items-center gap-4"
    >
      <!-- 已停止招聘状态 -->
      <view v-if="jobInfo.releaseStatus == 5" class="flex items-center flex-1">
        <IconFont font-class-name="iconfont" class-prefix="icon" name="xinxiinfo21" size="20" class="text-[#ff9900] mr-[10rpx]" />
        <text class="text-[28rpx] text-[#ff9900]">已停止招聘，无法报名</text>
      </view>
      <!-- 正常状态 -->
      <template v-else>
        <nut-button
          class="flex-1"
          type="success"
          @click="showContactInfo"
        >
         <template #icon>
            <IconFont name="message" size="28rpx" class="mr-[10rpx]" />
         </template>
          在线咨询
        </nut-button>
        
        <nut-button 
          type="info"
          class="flex-1"
          @click="applyForJob"
          v-if="jobInfo.memberStatus == 0"
        >
          立即报名
        </nut-button>
        <nut-button 
          class="flex-1"
          disabled
          v-else
        >
          已报名
        </nut-button>
      </template>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { showToast } from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { post } from "@/utils/request";
import Taro from "@tarojs/taro";
import { useUserStore } from "@/store/user";

// 职位信息接口定义
interface JobDetail {
  id: number;
  corporate_name?: string;
  deadline?: string;
  description?: string;
  experience?: string;
  location?: string;
  position_name?: string;
  salary_max?: string;
  salary_min?: string;
  type?: number;
  labels?: string;
  recruitmentType?: number;
  create_time?: string;
  contactPhone?: string;
  contactEmail?: string;
  releaseStatus?: number;
  memberStatus?: number;
  [property: string]: any;
  member_id?:number,
  name?:string
}

// 职位类型数据
const jobTypes = ref([
  { id: 1, type: "普工" },
  { id: 2, type: "技工" },
  { id: 3, type: "管理" },
  { id: 4, type: "质检" },
  { id: 5, type: "仓储" },
  { id: 6, type: "后勤" },
  { id: 7, type: "其他" },
]);

// 职位详情数据
const jobInfo = ref<JobDetail>({
  id: 0,
  recruitmentType: 0,
  position_name: "SMT技术员",
  salary_min: "6500",
  salary_max: "8500",
  location: "松江区",
  experience: "2年以上经验",
  type: 2,
  corporate_name: "中芯科技制造厂",
  create_time: "2025-08-01T08:30:00",
  description:
    "1. 负责SMT生产线的日常操作与维护\n2. 确保生产设备的正常运行，及时处理设备故障\n3. 按照生产计划完成生产任务，保证产品质量\n4. 记录生产数据，提交每日生产报告\n5. 参与生产线的改进与优化工作",
  labels: "SMT,技术员,电子,制造业",
  contactPhone: "13800138000",
  contactEmail: "hr@zhongxin-tech.com",
});

// 计算属性：获取职位类型文本
const jobTypeText = computed(() => {
  const typeItem = jobTypes.value.find(
    (item) => item.id === jobInfo.value?.type
  );
  return typeItem?.type || "未知类型";
});

// 页面加载时获取职位详情
const onLoad = async () => {
  // 获取页面参数中的职位ID
  const { id } = Taro.getCurrentInstance().router?.params || {};

  if (id) {
    try {
      Taro.showLoading({ title: "加载中..." });
      const res = await post("/recruitment/getById", { id });
      console.log('任务详情==>',res);
      if (res.code === 0) {
        jobInfo.value = res.data.columns || {};
      } else {
        showToast({ title: "获取职位信息失败", icon: "none" });
      }
    } catch (error) {
      showToast({ title: "网络错误，请重试", icon: "none" });
    } finally {
      Taro.hideLoading();
    }
  }
};

// 初始化页面
onLoad();

// 格式化发布时间
const formatPublishTime = (timeString?: string) => {
  // console.log('11==>',timeString)
  if (!timeString) return "未知时间";

  const publishTime = new Date(timeString);
  const now = new Date();
  const diffMs = now.getTime() - publishTime.getTime();
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

  if (diffDays === 0) {
    return "今天";
  } else if (diffDays === 1) {
    return "昨天";
  } else if (diffDays < 7) {
    return `${diffDays}天前`;
  } else {
    return `${publishTime.getMonth() + 1}月${publishTime.getDate()}日`;
  }
};

// 接收路由参数
const id = Taro.getCurrentInstance().router?.params.id;

// 申请职位
const applyForJob = async () => {
  // API
  const res = await post("/recruitment/signUp", {
    recruitmentId: id,
  });
  console.log('申请情况==>',res)
  if (res.code == 0) {
    // 这里可以跳转到申请表单页面或直接提交申请
    showToast({ title: "申请已提交，等待企业回复", icon: "none" });
    setTimeout(() => {
      Taro.navigateBack();
    }, 1200);
  } else {
    showToast({ title: res.data, icon: "none" });
  }
};

// 显示联系方式
const showContactInfo = () => {
  // 获取用户信息
  const userStore = useUserStore()
  
  // 检查是否是发布者本人
  if (jobInfo.value.member_id == userStore.userInfo.id) {
    showToast({ 
      title: "不能与自己聊天", 
      icon: "none",
      duration: 2000
    })
    return
  }
  
  showToast({ title: "正在打开聊天窗口...", icon: "none" });
  console.log('xxx ===>',jobInfo.value)
  // 跳转聊天页面
  Taro.navigateTo({
    url:`/pages/message/chat?userId=${jobInfo.value.member_id}&userName=${jobInfo.value.name}`
  })
};

// // 请求招聘详情信息
// const getRecruitmentById = async (id:number) => {
//   const res = await post('/recruitment/getById',{id})
// }
//
</script>

<style>
.job-detail-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 导航栏样式 */
.navbar {
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn,
.share-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 职位卡片样式 */
.job-card {
  border-radius: 16rpx;
  position: relative;
}

.recruitment-tag {
  position: absolute;
  top: 30rpx;
  right: 30rpx;
  background-color: #ff4d4f;
  color: white;
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.job-title {
  color: #333;
}

.salary {
  color: #f44336;
}

/* 公司信息样式 */
.company-logo {
  background-color: #f0f0f0;
}

.company-name {
  color: #333;
}

/* 详情区块样式 */
.section-title {
  color: #333;
  position: relative;
}

.section-title::after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  width: 60rpx;
  height: 4rpx;
  background-color: #1976d2;
}

/* 底部操作栏 */
.bottom-bar {
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.contact-btn,
.apply-btn {
  height: 90rpx;
  font-size: 30rpx;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
